<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="小程序," />





  <link rel="alternate" href="/atom.xml" title="尛孟的博客" type="application/atom+xml" />






<meta name="description" content="小程序提供的原生API可以方便的调起微信提供的能力 大部分接口都有以下共性   wx.on 开头的 API 是监听某个事件发生的API接口，接受一个 CALLBACK 函数作为参数。当该事件触发时，会调用 CALLBACK 函数。  如未特殊约定，其他 API 接口都接受一个OBJECT作为参数。  OBJECT中可以指定success, fail, complete函数来接收接口调用结果。">
<meta name="keywords" content="小程序">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序-API-网络">
<meta property="og:url" content="http://yoursite.com/2018/01/16/小程序-API-网络/index.html">
<meta property="og:site_name" content="尛孟的博客">
<meta property="og:description" content="小程序提供的原生API可以方便的调起微信提供的能力 大部分接口都有以下共性   wx.on 开头的 API 是监听某个事件发生的API接口，接受一个 CALLBACK 函数作为参数。当该事件触发时，会调用 CALLBACK 函数。  如未特殊约定，其他 API 接口都接受一个OBJECT作为参数。  OBJECT中可以指定success, fail, complete函数来接收接口调用结果。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-16T12:35:07.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="小程序-API-网络">
<meta name="twitter:description" content="小程序提供的原生API可以方便的调起微信提供的能力 大部分接口都有以下共性   wx.on 开头的 API 是监听某个事件发生的API接口，接受一个 CALLBACK 函数作为参数。当该事件触发时，会调用 CALLBACK 函数。  如未特殊约定，其他 API 接口都接受一个OBJECT作为参数。  OBJECT中可以指定success, fail, complete函数来接收接口调用结果。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'ZNJ0RM31SP',
      apiKey: '9fae47ade11c769ab25bba4061522c1d',
      indexName: 'for_meng',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":" 找不到关于 ”${query}“ 的文章 ","hits_stats":" 共找到${hits} 篇文章,花了${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/01/16/小程序-API-网络/"/>




<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">


  <title>小程序-API-网络 | 尛孟的博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">尛孟的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">想法总是无法付诸实践…</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/01/16/小程序-API-网络/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="尛孟">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="尛孟的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">小程序-API-网络</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-16T17:55:29+08:00">
                2018-01-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/小程序/" itemprop="url" rel="index">
                    <span itemprop="name">小程序</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/小程序/框架学习/" itemprop="url" rel="index">
                    <span itemprop="name">框架学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/小程序/框架学习/API/" itemprop="url" rel="index">
                    <span itemprop="name">API</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/01/16/小程序-API-网络/" class="leancloud_visitors" data-flag-title="小程序-API-网络">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<blockquote>
<p>小程序提供的原生API可以方便的调起微信提供的能力</p>
<p>大部分接口都有以下共性</p>
<blockquote>
<ul>
<li><p>wx.on 开头的 API 是监听某个事件发生的API接口，接受一个 CALLBACK 函数作为参数。当该事件触发时，会调用 CALLBACK 函数。</p>
</li>
<li><p>如未特殊约定，其他 API 接口都接受一个OBJECT作为参数。</p>
</li>
<li><p>OBJECT中可以指定<code>success, fail, complete</code>函数来接收接口调用结果。</p>
<p><strong><em>注：文件的临时路径，在小程序本次启动期间可以正常使用，如需持久保存，需在主动调用 <code>wx.saveFile</code>，才能在小程序下次启动时访问得到。</em></strong></p>
</li>
</ul>
</blockquote>
</blockquote>
<hr>
<h3 id="微信网络API规定"><a href="#微信网络API规定" class="headerlink" title="微信网络API规定"></a>微信网络API规定</h3><blockquote>
<p>1.每个微信小程序需要事先在小程序后台设置一个通讯<strong>域名</strong>(只能用域名而且需要经过ICP备案)，小程序可以跟指定的域名与进行网络通信</p>
<p>2.超时时间都是60s,最大并发数是10个,网络请求的<code>referer</code>header 不可设置。其格式固定为 <a href="https://servicewechat.com/{appid}/{version}/page-frame.html" target="_blank" rel="noopener">https://servicewechat.com/{appid}/{version}/page-frame.html</a></p>
<p>3.服务器返回建议使用UTF-8编码</p>
</blockquote>
<hr>
<h4 id="wx-request-OBJECT"><a href="#wx-request-OBJECT" class="headerlink" title="wx.request(OBJECT)"></a>wx.request(OBJECT)</h4><blockquote>
<p>发情网络请求,通过method参数设置请求方式<code>OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT</code></p>
<p>发送给服务器的数据是<code>String</code></p>
<p><strong>注意</strong>: url 中不能有端口</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> requestTask = wx.request(&#123;</span><br><span class="line">  url: <span class="string">'test.php'</span>, <span class="comment">//接口地址</span></span><br><span class="line">  <span class="comment">//参数列表</span></span><br><span class="line">  data: &#123;</span><br><span class="line">     x: <span class="string">''</span> ,</span><br><span class="line">     y: <span class="string">''</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//请求头</span></span><br><span class="line">  header: &#123;</span><br><span class="line">      <span class="string">'content-type'</span>: <span class="string">'application/json'</span></span><br><span class="line">  &#125;,</span><br><span class="line">   <span class="comment">//请求成功回调</span></span><br><span class="line">  success: <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res.data)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//可以使用request方法返回的task对象取消网络任务</span></span><br><span class="line">requestTask.abort() <span class="comment">// 取消请求任务</span></span><br></pre></td></tr></table></figure>
<hr>
<h4 id="wx-uploadFile-OBJECT"><a href="#wx-uploadFile-OBJECT" class="headerlink" title="wx.uploadFile(OBJECT)"></a>wx.uploadFile(OBJECT)</h4><blockquote>
<p>上传文件到服务器 , <code>content-type 为 multipart/form-data</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//本地选择照片</span></span><br><span class="line">wx.chooseImage(&#123;</span><br><span class="line">  success: <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//资源临时文件路径</span></span><br><span class="line">    <span class="keyword">var</span> tempFilePaths = res.tempFilePaths</span><br><span class="line">    <span class="keyword">const</span> uploadTask = wx.uploadFile(&#123;</span><br><span class="line">      url: <span class="string">'https://example.weixin.qq.com/upload'</span>, <span class="comment">//接口地址</span></span><br><span class="line">      <span class="comment">//文件路径</span></span><br><span class="line">      filePath: tempFilePaths[<span class="number">0</span>],</span><br><span class="line">      <span class="comment">//接受文件的key</span></span><br><span class="line">      name: <span class="string">'file'</span>,</span><br><span class="line">      <span class="comment">//其他参数</span></span><br><span class="line">      formData:&#123;</span><br><span class="line">        <span class="string">'user'</span>: <span class="string">'test'</span></span><br><span class="line">      &#125;,</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> data = res.data</span><br><span class="line">        <span class="comment">//do something</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//通过 uploadTask，可监听上传进度变化事件，以及取消上传任务。</span></span><br><span class="line">    uploadTask.onProgressUpdate(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">'上传进度'</span>, res.progress)</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">'已经上传的数据长度'</span>, res.totalBytesSent)</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">'预期需要上传的数据总长度'</span>, res.totalBytesExpectedToSend)</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br><span class="line">	uploadTask.abort() <span class="comment">// 取消上传任务</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<hr>
<h4 id="wx-downloadFile-OBJECT"><a href="#wx-downloadFile-OBJECT" class="headerlink" title="wx.downloadFile(OBJECT)"></a>wx.downloadFile(OBJECT)</h4><blockquote>
<p>下载文件到本地</p>
<p>下载后的文件会存储到一个临时文件</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> downloadTask = wx.downloadFile(&#123;</span><br><span class="line">  url: <span class="string">'https://example.com/audio/123'</span>, <span class="comment">//仅为示例，并非真实的资源</span></span><br><span class="line">  success: <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容</span></span><br><span class="line">    <span class="keyword">if</span> (res.statusCode === <span class="number">200</span>) &#123;</span><br><span class="line">        wx.playVoice(&#123;</span><br><span class="line">          filePath: res.tempFilePath</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//通过 downloadTask，可监听下载进度变化事件，以及取消下载任务</span></span><br><span class="line">  downloadTask.onProgressUpdate(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'下载进度'</span>, res.progress)   <span class="comment">//下载进度百分比</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'已经下载的数据长度'</span>, res.totalBytesWritten)   <span class="comment">//单位Bytes</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'预期需要下载的数据总长度'</span>, res.totalBytesExpectedToWrite) <span class="comment">// 单位 Bytes</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">downloadTask.abort() <span class="comment">// 取消下载任务</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<hr>
<h4 id="wx-connectSocket-OBJECT"><a href="#wx-connectSocket-OBJECT" class="headerlink" title="wx.connectSocket(OBJECT)"></a>wx.connectSocket(OBJECT)</h4><blockquote>
<p>创建一个 WebSocket 连接</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">wx.connectSocket(&#123;</span><br><span class="line">  url: <span class="string">'wss://example.qq.com'</span>,  <span class="comment">//websocket地址</span></span><br><span class="line">  data:&#123;</span><br><span class="line">    x: <span class="string">''</span>,</span><br><span class="line">    y: <span class="string">''</span></span><br><span class="line">  &#125;,</span><br><span class="line">  header:&#123; </span><br><span class="line">    <span class="string">'content-type'</span>: <span class="string">'application/json'</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//子协议数组    这样做可以让一个服务器实现多种WebSocket子协议来处理不同类型的交互</span></span><br><span class="line">  protocols: [<span class="string">'protocol1'</span>],</span><br><span class="line">  method:<span class="string">"GET"</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h5 id="wx-onSocketOpen-CALLBACK"><a href="#wx-onSocketOpen-CALLBACK" class="headerlink" title="wx.onSocketOpen(CALLBACK)"></a>wx.onSocketOpen(CALLBACK)</h5><blockquote>
<p>监听webSocket连接打开事件</p>
</blockquote>
<h5 id="wx-onSocketError-CALLBACK"><a href="#wx-onSocketError-CALLBACK" class="headerlink" title="wx.onSocketError(CALLBACK)"></a>wx.onSocketError(CALLBACK)</h5><blockquote>
<p>监听webSocket错误</p>
</blockquote>
<h5 id="wx-sendSocketMessage-OBJECT"><a href="#wx-sendSocketMessage-OBJECT" class="headerlink" title="wx.sendSocketMessage(OBJECT)"></a>wx.sendSocketMessage(OBJECT)</h5><blockquote>
<p>通过WebSocket连接发送数据,要先 <code>wx.connectSocket</code>，并在 <code>wx.onSocketOpen</code>回调之后才能发送。</p>
</blockquote>
<h5 id="wx-onSocketMessage-CALLBACK"><a href="#wx-onSocketMessage-CALLBACK" class="headerlink" title="wx.onSocketMessage(CALLBACK)"></a>wx.onSocketMessage(CALLBACK)</h5><blockquote>
<p>监听WebSocket接收到服务器的消息事件 (data)</p>
</blockquote>
<h5 id="wx-closeSocket-OBJECT"><a href="#wx-closeSocket-OBJECT" class="headerlink" title="wx.closeSocket(OBJECT)"></a>wx.closeSocket(OBJECT)</h5><blockquote>
<p>关闭WebSocket连接</p>
</blockquote>
<h5 id="wx-onSocketClose-CALLBACK"><a href="#wx-onSocketClose-CALLBACK" class="headerlink" title="wx.onSocketClose(CALLBACK)"></a>wx.onSocketClose(CALLBACK)</h5><blockquote>
<p>监听WebSocket关闭</p>
</blockquote>
<p><strong><em><code>除了上述的监听方法,connectSocket本身会返回一个webSocketTask任务 , 也可以发送消息监听事件等</code></em></strong></p>
<hr>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/小程序/" rel="tag"># 小程序</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/16/小程序-组件-地图-画布/" rel="next" title="小程序-组件-地图&画布">
                <i class="fa fa-chevron-left"></i> 小程序-组件-地图&画布
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/16/小程序-API-媒体/" rel="prev" title="小程序-API-媒体">
                小程序-API-媒体 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">尛孟</p>
              <p class="site-description motion-element" itemprop="description">与人联系甚少</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#微信网络API规定"><span class="nav-number">1.</span> <span class="nav-text">微信网络API规定</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#wx-request-OBJECT"><span class="nav-number">1.1.</span> <span class="nav-text">wx.request(OBJECT)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#wx-uploadFile-OBJECT"><span class="nav-number">1.2.</span> <span class="nav-text">wx.uploadFile(OBJECT)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#wx-downloadFile-OBJECT"><span class="nav-number">1.3.</span> <span class="nav-text">wx.downloadFile(OBJECT)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#wx-connectSocket-OBJECT"><span class="nav-number">1.4.</span> <span class="nav-text">wx.connectSocket(OBJECT)</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#wx-onSocketOpen-CALLBACK"><span class="nav-number">1.4.1.</span> <span class="nav-text">wx.onSocketOpen(CALLBACK)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#wx-onSocketError-CALLBACK"><span class="nav-number">1.4.2.</span> <span class="nav-text">wx.onSocketError(CALLBACK)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#wx-sendSocketMessage-OBJECT"><span class="nav-number">1.4.3.</span> <span class="nav-text">wx.sendSocketMessage(OBJECT)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#wx-onSocketMessage-CALLBACK"><span class="nav-number">1.4.4.</span> <span class="nav-text">wx.onSocketMessage(CALLBACK)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#wx-closeSocket-OBJECT"><span class="nav-number">1.4.5.</span> <span class="nav-text">wx.closeSocket(OBJECT)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#wx-onSocketClose-CALLBACK"><span class="nav-number">1.4.6.</span> <span class="nav-text">wx.onSocketClose(CALLBACK)</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">尛孟</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.4"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("KhsxPkrt4UYiKBnwYFY9zUTN-gzGzoHsz", "a1zezRocQqcmPxlFVdXKrhz9");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
